//index.js
//获取应用实例
const app = getApp();
const dateTimePicker = require('../../utils/dateTimePicker.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    projects: [],
    isHideLoadMore: true,
    totalProject: '',
    all_areas: '',
    all_suits: '',
    page: 1,
    showModalStatus: false,
    dateTimeArray: null,
    dateTime: null,
    dateTimeArray1: null,
    dateTime1: null,
    startYear: 2000,
    endYear: '2050',
    end_date: '',
    start_date: '',
    showModal: false,
    inputValue: '',
    isOk: 0,
    showAdd: true
  },

  getUserInfo: function () {

    let _that = this;
    app.getToken().then(function (){
      _that.loadData();
    });
  },

  loadData: function (){
    var _that = this;
    var userToken = wx.getStorageSync('user_token');
    let _isChecked = false;

    wx.request({
      url: app.globalData.requestUrl + 'api/get/userinfo',
      method: 'POST',
      data: {
        user_token: userToken
      },
      success: function (res) {
        if (res.data.status != 1) {
          wx.showToast({
            title: res.data.msg
          })
        } else {
          var resInfo = res.data.data.info;

          var _userInfo = null,
            _isChecked = false;
          if (resInfo) {
            _userInfo = resInfo;
            if (_userInfo.status == 1) {
              _isChecked = true;
            }
          }

          wx.setStorageSync('user_info', _userInfo);

          wx.setStorageSync('user_is_checked', _isChecked);

          app.globalData.isChecked = _isChecked;
          app.globalData.userInfo = _userInfo;

          if (_isChecked) {

            _that.setData({
              isOk: 1
            });
          } else {

            wx.redirectTo({
              'url': '/pages/sign/up'
            });
          }
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;

    this.getUserInfo();

    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: app.globalData.requestUrl + 'api/project/mine',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
      },
      success: function (res) {
        // console.log(res.data.data.projects.data,);
        let temp_project = res.data.data.projects.data;

        //统计每个项目向所有产品的面积和套数
        for (let value of temp_project) {

          let area = 0,
              suit = 0;
          for (var item of value.products) {
            // console.log(item.area)
            area += item.area;
            suit += item.tao;
            value['area'] = area;
            value['suit'] = suit;
          }
        }

        wx.hideLoading()
        // 执行成功
        that.setData({
          projects: res.data.data.projects.data,
          totalProject: res.data.data.projects.total,
          page: res.data.data.projects.current_page,
          all_areas: res.data.data.tongji.all_area,
          all_suits: res.data.data.tongji.all_tao
        })

      }, fail: function () {

        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });


    // 获取完整的年月日 时分秒，以及默认显示的数组
    let obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    let obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    // 精确到分的处理，将数组的秒去掉
    let lastArray = obj1.dateTimeArray.pop();
    let lastTime = obj1.dateTime.pop();
    let end_date = obj1.dateTimeArray[0][obj1.dateTime[0]] + '-' + obj1.dateTimeArray[1][obj1.dateTime[1]] + '-' + obj1.dateTimeArray[2][obj1.dateTime[2]];
    let start_date = obj1.dateTimeArray[0][obj1.dateTime[0]] + '-' + obj1.dateTimeArray[1][obj1.dateTime[1]] + '-' + obj1.dateTimeArray[2][obj1.dateTime[2]];

    that.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
      dateTimeArray1: obj1.dateTimeArray,
      dateTime1: obj1.dateTime,
      end_date: end_date,
      start_date: start_date
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.onLoad()
    var userInfo = wx.getStorageSync('user_info');
    let showAdd = userInfo.role == 0 ? false : true; 
    this.setData({
      showModalStatus: false,
      showAdd: showAdd
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //添加项目
  insertProject: function () {
    app.addProject();
  },

  //搜索框输入
  bindconfirm: function (e) {
    const that = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: app.globalData.requestUrl + 'api/project/all',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
        keyword: e.detail.value
      },
      success: function (res) {
        // console.log(res.data.data.projects.data,);
        let temp_project = res.data.data.projects.data;

        //统计每个项目向所有产品的面积和套数
        for (let value of temp_project) {

          let area = 0,
              suit = 0;
          for (var item of value.products) {
            // console.log(item.area)
            area += item.area;
            suit += item.tao;
            value['area'] = area;
            value['suit'] = suit;
          }

        }

        wx.hideLoading()
        // 执行成功
        that.setData({
          projects: res.data.data.projects.data,
          totalProject: res.data.data.projects.total,
          page: res.data.data.projects.current_page,
          all_areas: res.data.data.tongji.all_area,
          all_suits: res.data.data.tongji.all_tao
        })

      }, fail: function () {

        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });



  },

  //下拉刷新
  onPullDownRefresh: function () {
    this.onLoad();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  //上拉加载更多
  onReachBottom: function () {

    const that = this;
    let projects = that.data.projects,
      page = that.data.page;
    wx.request({
      url: app.globalData.requestUrl + 'api/project/all',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
        page: page + 1
      },
      success: function (res) {
        wx.hideLoading()
        // 执行成功
        that.setData({
          isHideLoadMore: true,
          projects: projects.concat(res.data.data.projects.data),
          totalProject: res.data.data.projects.total,
          page: res.data.data.projects.current_page,
          all_areas: res.data.data.tongji.all_area,
          all_suits: res.data.data.tongji.all_tao
        })

      }, fail: function () {
        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });

    //加载状态再次初始化
    this.setData({
      isHideLoadMore: false
    })

  },


  //时间模糊查询 弹出层
  powerDrawer: function (e) {
    let currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  util: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例   
    let animation = wx.createAnimation({
      duration: 200,  //动画时长  
      timingFunction: "linear", //线性  
      delay: 0  //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })

      //关闭  
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)

    // 显示  
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  },

  //模糊查询设置开始时间
  changeDateTimeStart: function (e) {
    let arr = this.data.dateTime1, dateArr = this.data.dateTimeArray1;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    let start_date = e.detail.value;

    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr,
      start_date: start_date
    });

  },

  //模糊查询设置结束时间
  changeDateTimeEnd: function (e) {
    let arr = this.data.dateTime1, dateArr = this.data.dateTimeArray1;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    let end_date = e.detail.value;

    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr,
      end_date: end_date
    });

  },

  changeDateTime1(e) {
    this.setData({ dateTime1: e.detail.value });
  },


  //选择时间后确定
  sureDate: function () {
    let start_date = this.data.start_date,
      end_date = this.data.end_date;
    // console.log((new Date(start_date) , new Date(end_date)))

    if ((start_date > end_date) || (start_date == end_date)) {

      wx.showToast({
        title: '结束时间必须大于开始时间',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: '/pages/componet/dateSearch/dateSearch?start_date=' + start_date + '&end_date=' + end_date,
    })

  },


  //创建项目
  /**
     * 弹窗
     */
  showDialogBtn: function () {
    this.setData({
      showModal: true
    })
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function () {
  },
  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function () {
    this.hideModal();
  },
  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function (e) {
    const that = this;
    let project_name = that.data.inputValue;
    if (project_name == '') {
      wx.showToast({
        title: '请输入项目名称',
        icon: 'none',
      });
      return;
    }
    that.hideModal();
    wx.showToast({
      title: '正在提交信息...',
      icon: 'none',
      duration: 200000
    });

    wx.request({
      url: app.globalData.requestUrl + 'api/project/create',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
        project_name: project_name,
      },

      success: function (res) {
        wx.hideToast();


        if (res.data.status == 1) {
          wx.showToast({
            title: '创建成功',
            icon: 'none',
          });
          that.onLoad()
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          });
        }

      }, fail: function () {

        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });

  },

  inputChange: function (e) {
    const that = this;
    that.setData({
      inputValue: e.detail.value
    })
  },
  //删除项目
  // delMerchandise: function (e) {
  //   console.log(e.currentTarget.id);
  //   const that = this;
  //   let id = e.currentTarget.id;
  //   wx.showModal({
  //     content: '这是一个模态弹窗',
  //     success: function (res) {
  //       if (res.confirm) {
  //         console.log('用户点击确定')
  //         wx.showToast({
  //           title: '正在提交信息...',
  //           icon: 'none',
  //           duration: 200000
  //         });
  //         wx.request({
  //           url: app.globalData.requestUrl + 'api/category/delete',
  //           method: 'POST',
  //           data: {
  //             user_token: app.globalData.userToken,
  //             id: id,
  //           },
  //           success: function (res) {
  //             wx.hideToast();
  //             // 执行成功
  //             that.setData({
  //               merchandise_array: res.data.data.categories
  //             })

  //           }, fail: function () {

  //             wx.showToast({
  //               title: '系统错误请稍后重试',
  //               icon: 'none'
  //             });
  //           }
  //         });

  //       } else if (res.cancel) {
  //         wx.showToast({
  //           title: '删除取消',
  //           icon: 'none',
  //         });
  //       }
  //     }
  //   })

})
